//  Copyright (c) 2010 Mahesh Sharma,Matt MacDonald
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

package org.prx.prp.view;

import org.prx.prp.R;
import org.prx.prp.utility.DatabaseAdapter;

import android.app.ExpandableListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SimpleCursorTreeAdapter;

public class StateListActivity extends ExpandableListActivity {
    
        private ExpandableListAdapter mAdapter;    
        private Context mContext;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	try
    	{
        super.onCreate(savedInstanceState);
        getExpandableListView().setHorizontalFadingEdgeEnabled(false);
        getExpandableListView().setBackgroundColor(Color.parseColor("#FFFFFF"));
        getExpandableListView().setCacheColorHint(Color.parseColor("#FFFFFF"));		
        String query="SELECT CASE WHEN STATE_PRIMARY='' THEN 'World' ELSE STATE_PRIMARY END AS STATE,(CASE WHEN STATE_PRIMARY='' THEN 'World' ELSE STATE_PRIMARY END ||' ('||COUNT(*)||')') as STATE_NAME,SCHEDULINGS.ID AS _id,STATE_PRIMARY FROM STREAMS LEFT OUTER JOIN SCHEDULINGS ON SCHEDULINGS.STREAM_ID = STREAMS.ID JOIN SOURCES ON STREAMS.SOURCE_ID=SOURCES.ID GROUP BY STATE";        
        Cursor groupCursor =DatabaseAdapter.executeQuery(query,null); 
        startManagingCursor(groupCursor);
        mContext=this;
       
        mAdapter = new MyExpandableListAdapter(groupCursor,
                this,
                 R.layout.my_expandable_list_item_1,
                R.layout.stream_info_item,
                new String[] {"STATE_NAME"}, // Name for group layouts
                new int[] {android.R.id.text1},
                new String[] {"STREAM_DISPLAY_NAME","PROGRAM_TITLE","TIME"}, // Number for child layouts
                new int[] {R.id.stream_name,R.id.program_title,R.id.schedule_time});
        setListAdapter(mAdapter);
        ExpandableListView expandableListView=getExpandableListView();
        setContentView(expandableListView);
        expandableListView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView arg0, View arg1, int group,
					int child, long arg4) {				
				Cursor cursor=(Cursor) mAdapter.getChild(group,child);
        		int programIDOfSelectedItem=cursor.getInt(cursor.getColumnIndex("STREAM_ID"));
        		String displayName=cursor.getString(cursor.getColumnIndex("STREAM_DISPLAY_NAME"));
        		Bundle bundle=new Bundle();
				bundle.putInt("STREAM_ID",programIDOfSelectedItem);
				bundle.putString("STREAM_DISPLAY_NAME",displayName);
				Intent intent=new Intent(mContext,StationInformationView.class);
				intent.putExtras(bundle);
				startActivity(intent);
				return false;
			}
		});
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace();
    	}
    }

    class MyExpandableListAdapter extends SimpleCursorTreeAdapter {
    	
        public MyExpandableListAdapter(Cursor cursor, Context context, int groupLayout,
                int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom,
                int[] childrenTo) {
            super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childrenFrom,
                    childrenTo);
        }

        @Override
        protected Cursor getChildrenCursor(Cursor groupCursor) {        	
        	String stateName=groupCursor.getString(groupCursor.getColumnIndex("STATE"));
        	Log.d("PRPAND", "stateName: " + stateName);
            Cursor cursor=DatabaseAdapter.executeQuery("SELECT TRIM(STREAMS.DISPLAY_NAME) AS STREAM_DISPLAY_NAME,STREAMS.ID AS STREAM_ID,SCHEDULINGS.ID as _id,SUBSTR(TIME(START_TIME,'localtime'),0,5)||' TO '||SUBSTR(TIME(END_TIME,'localtime'),0,5) AS TIME,PROGRAMS.TITLE AS PROGRAM_TITLE,PROGRAM_ID FROM STREAMS LEFT OUTER JOIN SCHEDULINGS ON STREAMS.ID= SCHEDULINGS.STREAM_ID LEFT OUTER JOIN PROGRAMS ON PROGRAMS.ID=SCHEDULINGS.PROGRAM_ID JOIN SOURCES ON STREAMS.SOURCE_ID=SOURCES.ID WHERE UPPER(STATE_PRIMARY) = UPPER('"+stateName+"')",null);            
            startManagingCursor(cursor);
            return cursor;                 
        }               
    }
}